package com.xframe.common.core.service.command;

import com.xframe.common.config.CommandRunTimeArgs;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.common.core.constant.ErrorConstant;
import com.xframe.domain.CommandModel;
import com.xframe.common.core.dto.ErrorCode;
import com.xframe.common.core.dto.ModelRepositoryDTO;
import com.xframe.common.core.exception.BusinessException;
import com.xframe.event.bus.core.model.DataMessage;
import com.xframe.event.bus.core.msg.MessageSender;
import com.xframe.xdal.core.model.IModel;
import com.xframe.xdal.core.model.mapping.ITableInfo;

import java.lang.reflect.Method;


public class UpdateProc extends BaseCommand {


    @Override
    public Object ProcCommand(CommandModel requestArgs, IUserCredentials userCredentials) throws BusinessException {
        try {
            ModelRepositoryDTO modelRepository = procRepository(requestArgs, userCredentials);

            Method method = this.getMethodByName(modelRepository.getRepository().getClass(), "update", IModel.class, ITableInfo.class);
            Integer updateRows = (Integer) this.execRepository(modelRepository.getRepository(), method,
                    modelRepository.getModel(), modelRepository.getSysModel());
            if (1 != updateRows) {
                throw new BusinessException(ErrorCode.SQL_ERROR, ErrorConstant.DB_OPERATOR_UPDATE_MSG);
            }
            IModel model = modelRepository.getModel();
            //发消息
            if(model.getObjectId() != null) {
                MessageSender messageSender = MessageSender.getMessageSender();
                if(messageSender != null) {
                    DataMessage dataMessage = DataMessage.valueOf(modelRepository.getSysModel().getModelCode(),
                            DataMessage.UPDATE, model.getObjectId().toString(),
                            null, model, requestArgs.getSysCode(), userCredentials.getName());
                    messageSender.sendMsg(CommandRunTimeArgs.getRunTimeArgs().getDataQueueName(), dataMessage);
                }
            }
            return model;
        } catch (Exception exception) {
            throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, exception.getMessage());
        }
    }

    @Override
    public String getBeanName() {
        return "Update";
    }
}
